
var Relative = {
    editIndex: -1,
    isDg: 0,
    dgType: undefined,
    goodsId :undefined,
    skuValue:undefined,
    goodsArr : [],

};




Relative.dg = function () {

    $.ajax({
        type: "GET",
        url: "/mMateriel/queryInvMaterielList",
        dataType: "json",
        success: function (data) {
            Relative.goodsArr = data;
        }
    });

    Relative.dtable = $('#relative_table');
    Relative.dtable.datagrid({
        // pagination: true,
        fitColumns: true,
        autoRowHeight: true,
        rownumbers: true,
        singleSelect: true,
        scrollbarSize:0,
        nowrap:false,
        toolbar: [
            {
                text: '增加', iconCls: 'icon-add', handler: function () {
                Relative.saveDgGoods();
                }
            },
            {
                text: '删除', iconCls: 'icon-remove', handler: function () {
                Relative.remove();
                }
            }
        ],
        columns: [[
            {field: 'skusId', checkbox: true},//仓储规格id
            {field: 'invSkuId', title: '<span style="color:deeppink">品名规格</span>', width: 340, halign: 'center',
                editor: {
                    type: 'combobox', options: {
                        mode: 'remote',
                        valueField: 'invSkuId',
                        textField: 'name',
                        nowrap: false,
                        url: "/mMateriel/queryInvMaterielList",
                        method: 'get',
                        onChange: function (value, row) {
                        // console.log(value)



                        },
                    }
            },  formatter: function (value, row, index) {
                for (var i = 0; i < Relative.goodsArr.length; i++) {
                    if (value == Relative.goodsArr[i].invSkuId) {
                        return Relative.goodsArr[i].name;
                    }
                }
                return value;
            }
            },
            {field: 'count', title: '<span style="color:deeppink">套餐中数量</span>', width: 80, halign: 'center',
                editor: {type: 'numberbox', options: {required: true, min: 1, precision: 0}}
            },

            {field: 'skuCode', title: '商品编码', halign: 'center', width: 140},
            {field: 'defaultSupplier', title: '默认供应商',  halign: 'center',width:200},
            {field: 'brand', title: '品牌',  halign: 'center',width:80},
            {field: 'repositoryCount', title: '库存量',  halign: 'center',width:80},
            {field: 'goodsId', title: '天天爱车商品ID',  halign: 'center',width:80,hidden:true},
            {field: 'skuValue', title: '天天爱车商品sku值',  halign: 'center',width:80,hidden:true},

        ]],
        onClickCell: function (index, field) {
            if (Relative.editIndex != index) {
                if (Relative.editIndex > -1) {
                    Relative.dtable.datagrid('endEdit', Relative.editIndex);
                }
                Relative.editIndex = index;
            }
            Relative.dtable.datagrid('beginEdit', index);
        },
        onEndEdit: function (index, row) {

            
            $.ajax({
                url:'/mMateriel/queryInvMaterielList',

                type:'get',
                data :{
                    invSkuId:row['invSkuId'],
                },
                async:false,
                success:function (data) {

                    var repositoryCountData = 0;
                    var brand = "";
                    var supplier = "";
                    var code = "";
                    repositoryCountData=data[0].count;
                    brand=data[0].brand;
                    supplier=data[0].defaultSupplier;
                    code=data[0].skuCode;
                    Relative.dtable.datagrid('updateRow', {

                        index: index ,
                        row: {
                            repositoryCount : repositoryCountData,
                            brand: brand,
                            defaultSupplier:supplier,
                            skuCode:code,
                        }
                    });


                }
            });


        }
    });
    Relative.dtable.datagrid('enableCellEditing');

};

Relative.saveDgGoods = function () {

    Relative.goodsId = $('#goodsId').val();
    Relative.skuValue = $('#skuValue').val();

    Relative.dtable.datagrid('appendRow', {
        invSkuId:":",
        goodsId: Relative.goodsId,
        skuValue:Relative.skuValue,
        count: 1
    }).datagrid('clearSelections');



    Relative.isDg = 0;
    Relative.dgType = undefined;

    // var list = $(":checkbox");
    // var tmp = 0;
    // for (var i = 1; i < list.length; i++) {
    //     var td = $(list[i]).closest("td");
    //     if (td.hasClass("datagrid-row-selected")) {
    //         tmp = i;
    //     }
    // }
    // if (tmp == 0) {
    //     $(list[1]).closest("td").trigger("click");
    // }
    //
    // $(":checkbox").attr("tabindex", -1);
};


Relative.isExist = function (rows, skusId) {
    for (var i = 0; i < rows.length; i++) {
        if (rows[i].skusId == skusId) {
            return true;
        }
    }
    return false;
};


Array.prototype.contains = function (needle) {
    for (var i in this) {
        if (this[i] == needle) return true;
    }
    return false;
};

//删除
Relative.remove = function () {
    var sels = Relative.dtable.datagrid('getChecked');
    if (sels.length == 0) {
        $yd.alert('请选中记录');
        return;
    }
    var ids = [];
    $.each(sels, function (i, n) {
        ids.push(n['invSkuId']);
    });

    $.each(ids, function (i, n) {
        var rows = Relative.dtable.datagrid('getRows');
        for (var ii = 0; ii < rows.length; ii++) {
            if (rows[ii].invSkuId == n) {
                Relative.dtable.datagrid('deleteRow', ii);
                break;
            }
        }
    });

    var tds = $(".datagrid-row-selected");
    if(tds.length==0) {
        var checks = $(":checkbox");
        if(checks.length>1) {
            $(checks[1]).closest("td").trigger("click");
        }
    }
};


Relative.isEmpty = function (value) {
    if (value == undefined || value == null || value == "") {
        return true;
    }
    return false;
};

Relative.save = function () {

    var rows = Relative.dtable.datagrid("getRows");
    for (var i =0;i< rows.length;i++){
        Relative.dtable.datagrid('endEdit', i);
    }



    $('#relativeForm').form('submit', {

        url: "/tticar/comboSubmit",
        onSubmit: function () {

            var isValid = $(this).form('validate');//只能校验处于编辑状态的栏位
            if (!isValid) {
                return isValid;
            }

            //校验数据
            var rows = Relative.dtable.datagrid("getRows");

            if (rows.length == 0) {
                $yd.alert("请添加存货");
                return false;
            }

            //封装数据
            $("#rowMessage").val(JSON.stringify(rows));
            return isValid;
        },
        success: function (data) {
            var d = $.parseJSON(data);
            if (d.code == 0) {
                $yd.alert("操作成功", function () {
                    window.location.reload();
                });
            }
        }

    });
};




Relative.init = function () {
    
    //鼠标点击页面任何地方，表格编辑结束编辑状态
    document.onclick = Relative.mouseClick;
    // setTimeout("$('#orderTime').focus()", 500);
    // $("a").attr("tabindex", -1);
    // $(":checkbox").attr("tabindex", -1);
};
Relative.mouseClick = function (e) {
    e = window.event || e; // 兼容IE7
    var obj = $(e.srcElement || e.target);

    if (Relative.isDg == 0 && !$(obj).hasClass("datagrid-cell") && !$(obj).hasClass("datagrid-row-over")) {
        if (Relative.editIndex != -1) {
            Relative.dtable.datagrid('endEdit', Relative.editIndex);
            Relative.editIndex = -1;
        }
    }
};
$(function () {
    Relative.dg(); // 数据表格

    Relative.init(); // 数据表格

});




//保存按钮
var resetBtn = document.getElementById("sure");
resetBtn.addEventListener("click", function() {
    Relative.save();
});

//取消按钮
// var resetBtn = document.getElementById("cancel");
// resetBtn.addEventListener("click", function() {
//     window.close();
// });
